package com.custom.jdbc.executebody;

import com.custom.comm.utils.AssertUtil;
import com.custom.jdbc.handler.TypeHandler;

import java.util.*;

/**
 * 基础执行体(只支持增删改)
 * @author  Xiao-Bai
 * @since  2022/6/17 21:50
 */
public class BaseSqlExecutorBody implements SqlExecutorBody {

    /**
     * 待执行的sql
     */
    private final String prepareSql;

    /**
     * 是否支持sql打印
     */
    private boolean sqlPrintSupport;
    /**
     * sql参数
     */
    private final Object[] sqlParams;

    private Class<?> mappedType = Object.class;
    private Map<String, TypeHandler<?>> fieldTypeHandlerMap;
    /**
     * 该列表为添加或修改时的<b>java</b>字段顺序
     * <br/> insert into table (id, name, age) values (?, ?, ?) -> {"id", "name", "age"}
     * <br/> update table set name = ?, age = ? where id = ? -> {"name", "age", "id"}
     */
    private List<String> updateFields;

    public BaseSqlExecutorBody(Class<?> mappedType, String prepareSql, boolean sqlPrintSupport, Object[] sqlParams) {
        AssertUtil.notEmpty(prepareSql, "The Sql to be Not Empty");
        if (mappedType != null) {
            this.mappedType = mappedType;
        }
        this.prepareSql = prepareSql;
        this.sqlPrintSupport = sqlPrintSupport;
        this.sqlParams = sqlParams;
    }

    public BaseSqlExecutorBody(String prepareSql, boolean sqlPrintSupport, Object[] sqlParams) {
        this(null, prepareSql, sqlPrintSupport, sqlParams);
    }

    public void setFieldTypeHandlerMap(Map<String, TypeHandler<?>> fieldTypeHandlerMap) {
        this.fieldTypeHandlerMap = fieldTypeHandlerMap;
    }



    public String getPrepareSql() {
        return prepareSql;
    }

    public boolean isSqlPrintSupport() {
        return sqlPrintSupport;
    }


    public BaseSqlExecutorBody setSqlPrintSupport(boolean sqlPrintSupport) {
        this.sqlPrintSupport = sqlPrintSupport;
        return this;
    }

    public Object[] getSqlParams() {
        if (Objects.isNull(this.sqlParams)) {
            return new Object[]{};
        }
        return sqlParams;
    }

    @Override
    public Map<String, TypeHandler<?>> getFieldTypeHandlerMap() {
        return fieldTypeHandlerMap;
    }

    public List<String> getUpdateFields() {
        return updateFields;
    }

    public void setUpdateFields(List<String> updateFields) {
        this.updateFields = updateFields;
    }

    public Class<?> getMappedType() {
        return mappedType;
    }
}
